package ru.jkff.jalgebra.core;

/**
 * User: jkff
 * Date: Aug 23, 2009
 * Time: 12:48:53 PM
 */
public abstract class Functions {
    private Functions() {}

    public static <X,Y> Function<X,Y> withDefault(
            final PartialFunction<X,Y> f,
            final Y defaultValue)
    {
        return new Function<X, Y>() {
            public Y apply(X x) {
                try {
                    return f.apply(x);
                } catch(IllegalArgumentException e) {
                    return defaultValue;
                }
            }
        };
    }

    public static <A,B,C> Function<A,C> then(final Function<A,B> first, final Function<B,C> second) {
        return new Function<A, C>() {
            public C apply(A a) {
                return second.apply(first.apply(a));
            }
        };
    }
    public static <A,B,C> Function<A,C> after(final Function<B,C> second, final Function<A,B> first) {
        return then(first,second);
    }
}
